package com.sddnytsh.body_buildingsystem.screens

import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.navigation.NavController
import com.sddnytsh.body_buildingsystem.data.state.UserState
import com.sddnytsh.body_buildingsystem.topic.CommunityPost
import com.sddnytsh.body_buildingsystem.network.CommunityApiService
import kotlinx.coroutines.launch
import java.text.SimpleDateFormat
import java.util.*
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun MyPostsScreen(navController: NavController) {
    val currentUser = UserState.currentUser
    var posts by remember { mutableStateOf<List<CommunityPost>>(emptyList()) }
    var isLoading by remember { mutableStateOf(false) }
    var isLoadingMore by remember { mutableStateOf(false) }
    var currentPage by remember { mutableStateOf(1) }
    var hasMore by remember { mutableStateOf(true) }
    var showDeleteDialog by remember { mutableStateOf(false) }
    var postToDelete by remember { mutableStateOf<CommunityPost?>(null) }
    
    val listState = rememberLazyListState()
    val coroutineScope = rememberCoroutineScope()
    val communityApiService = remember { CommunityApiService() }
    val gson = remember { Gson() }
    
    // 加载数据
    fun loadPosts(refresh: Boolean = false) {
        if (currentUser == null) return
        
        coroutineScope.launch {
            if (refresh) {
                currentPage = 1
                hasMore = true
                isLoading = true
            } else {
                isLoadingMore = true
            }
            
            try {
                val result = communityApiService.getUserPosts(currentUser.id, currentPage, 10)
                result.onSuccess { data ->
                    android.util.Log.d("MyPostsScreen", "API响应数据: $data")
                    val postsData = data["posts"] as? List<Map<String, Any>> ?: emptyList()
                    val hasMoreData = data["hasMore"] as? Boolean ?: false
                    
                    android.util.Log.d("MyPostsScreen", "解析的帖子数据: $postsData")
                    
                    val newPosts = postsData.map { postData ->
                        android.util.Log.d("MyPostsScreen", "单个帖子数据: $postData")
                        CommunityPost(
                            id = (postData["id"] as? Double)?.toLong() ?: 0L,
                            userId = (postData["userId"] as? Double)?.toLong() ?: 0L,
                            author = postData["author"] as? String,
                            title = postData["title"] as? String,
                            content = postData["content"] as? String,
                            likeCount = (postData["likeCount"] as? Double)?.toInt() ?: 0,
                            favoriteCount = (postData["favoriteCount"] as? Double)?.toInt() ?: 0,
                            commentCount = (postData["commentCount"] as? Double)?.toInt() ?: 0,
                            isLiked = postData["isLiked"] as? Boolean ?: false,
                            isFavorited = postData["isFavorited"] as? Boolean ?: false,
                            createdAt = postData["createdAt"] as? String,
                            updatedAt = postData["updatedAt"] as? String
                        )
                    }
                    
                    android.util.Log.d("MyPostsScreen", "解析后的帖子: $newPosts")
                    
                    posts = if (refresh) {
                        newPosts
                    } else {
                        posts + newPosts
                    }
                    
                    hasMore = hasMoreData
                    currentPage++
                }.onFailure { error ->
                    android.util.Log.e("MyPostsScreen", "加载帖子失败", error)
                    // 如果API失败，使用模拟数据
                    val mockPosts = if (refresh) {
                        generateMockPosts(currentUser.id)
                    } else {
                        posts + generateMockPosts(currentUser.id, currentPage)
                    }
                    posts = mockPosts
                    currentPage++
                    hasMore = mockPosts.size >= 10
                }
                
            } catch (e: Exception) {
                android.util.Log.e("MyPostsScreen", "加载帖子异常", e)
                // 如果出现异常，使用模拟数据
                val mockPosts = if (refresh) {
                    generateMockPosts(currentUser.id)
                } else {
                    posts + generateMockPosts(currentUser.id, currentPage)
                }
                posts = mockPosts
                currentPage++
                hasMore = mockPosts.size >= 10
            } finally {
                isLoading = false
                isLoadingMore = false
            }
        }
    }
    
    // 删除帖子
    fun deletePost(post: CommunityPost) {
        coroutineScope.launch {
            try {
                val result = communityApiService.deletePost(post.id, currentUser?.id ?: 0L)
                result.onSuccess { 
                    posts = posts.filter { it.id != post.id }
                    showDeleteDialog = false
                    postToDelete = null
                    android.util.Log.d("MyPostsScreen", "删除帖子成功")
                }.onFailure { error ->
                    android.util.Log.e("MyPostsScreen", "删除帖子失败", error)
                    // 即使API失败，也从本地列表中移除（用户体验）
                    posts = posts.filter { it.id != post.id }
                    showDeleteDialog = false
                    postToDelete = null
                }
            } catch (e: Exception) {
                android.util.Log.e("MyPostsScreen", "删除帖子异常", e)
                // 即使出现异常，也从本地列表中移除
                posts = posts.filter { it.id != post.id }
                showDeleteDialog = false
                postToDelete = null
            }
        }
    }
    
    // 初始加载
    LaunchedEffect(currentUser) {
        if (currentUser != null) {
            loadPosts(true)
        }
    }
    
    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text("我的发帖") },
                navigationIcon = {
                    IconButton(onClick = { navController.popBackStack() }) {
                        Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "返回")
                    }
                },
                colors = TopAppBarDefaults.topAppBarColors(
                    containerColor = Color(0xFF4361EE),
                    titleContentColor = Color.White,
                    navigationIconContentColor = Color.White
                )
            )
        }
    ) { paddingValues ->
        Box(
            modifier = Modifier
                .fillMaxSize()
                .padding(paddingValues)
        ) {
            if (isLoading && posts.isEmpty()) {
                // 初始加载状态
                Box(
                    modifier = Modifier.fillMaxSize(),
                    contentAlignment = Alignment.Center
                ) {
                    CircularProgressIndicator(color = Color(0xFF4361EE))
                }
            } else if (posts.isEmpty()) {
                // 空状态
                EmptyPostsState()
            } else {
                // 帖子列表
                LazyColumn(
                    state = listState,
                    modifier = Modifier.fillMaxSize(),
                    contentPadding = PaddingValues(16.dp),
                    verticalArrangement = Arrangement.spacedBy(12.dp)
                ) {
                    items(posts) { post ->
                        MyPostItem(
                            post = post,
                            onEditClick = { 
                                // TODO: 跳转到编辑页面
                                // navController.navigate("editPost/${post.id}")
                            },
                            onDeleteClick = { 
                                postToDelete = post
                                showDeleteDialog = true
                            },
                            onCommentClick = {
                                // 跳转到帖子详情页面查看评论
                                navController.navigate("postDetail/${post.id.toInt()}")
                            }
                        )
                    }
                    
                    // 加载更多
                    if (isLoadingMore) {
                        item {
                            Box(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .padding(16.dp),
                                contentAlignment = Alignment.Center
                            ) {
                                CircularProgressIndicator(
                                    modifier = Modifier.size(24.dp),
                                    color = Color(0xFF4361EE)
                                )
                            }
                        }
                    }
                }
            }
        }
    }
    
    // 删除确认对话框
    if (showDeleteDialog && postToDelete != null) {
        AlertDialog(
            onDismissRequest = { 
                showDeleteDialog = false
                postToDelete = null
            },
            title = { Text("确认删除") },
            text = { Text("确定要删除这篇帖子吗？删除后无法恢复。") },
            confirmButton = {
                TextButton(
                    onClick = { 
                        postToDelete?.let { deletePost(it) }
                    },
                    colors = ButtonDefaults.textButtonColors(
                        contentColor = Color(0xFFD32F2F)
                    )
                ) {
                    Text("删除")
                }
            },
            dismissButton = {
                TextButton(
                    onClick = { 
                        showDeleteDialog = false
                        postToDelete = null
                    }
                ) {
                    Text("取消")
                }
            }
        )
    }
}

@Composable
fun EmptyPostsState() {
    Box(
        modifier = Modifier.fillMaxSize(),
        contentAlignment = Alignment.Center
    ) {
        Column(
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            Icon(
                imageVector = Icons.Default.Edit,
                contentDescription = "空状态",
                modifier = Modifier.size(64.dp),
                tint = Color(0xFF6C757D)
            )
            Spacer(modifier = Modifier.height(16.dp))
            Text(
                text = "你还没有发过帖子",
                style = MaterialTheme.typography.headlineSmall,
                fontWeight = FontWeight.Bold,
                color = Color(0xFF212529)
            )
            Spacer(modifier = Modifier.height(8.dp))
            Text(
                text = "快去分享你的健身心得吧！",
                style = MaterialTheme.typography.bodyMedium,
                color = Color(0xFF6C757D)
            )
        }
    }
}

@Composable
fun MyPostItem(
    post: CommunityPost,
    onEditClick: () -> Unit,
    onDeleteClick: () -> Unit,
    onCommentClick: () -> Unit
) {
    Card(
        modifier = Modifier.fillMaxWidth(),
        colors = CardDefaults.cardColors(containerColor = Color.White),
        shape = RoundedCornerShape(12.dp),
        elevation = CardDefaults.cardElevation(defaultElevation = 2.dp)
    ) {
        Column(
            modifier = Modifier.padding(16.dp)
        ) {
            // 标题
            Text(
                text = post.title ?: "无标题",
                style = MaterialTheme.typography.titleMedium.copy(
                    fontWeight = FontWeight.Bold
                ),
                color = Color(0xFF212529),
                maxLines = 2,
                overflow = TextOverflow.Ellipsis
            )
            
            Spacer(modifier = Modifier.height(8.dp))
            
            // 内容摘要
            Text(
                text = post.content ?: "",
                style = MaterialTheme.typography.bodyMedium,
                color = Color(0xFF6C757D),
                maxLines = 3,
                overflow = TextOverflow.Ellipsis
            )
            
            Spacer(modifier = Modifier.height(12.dp))
            
            // 统计信息和操作
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
                // 统计信息
                Row(
                    verticalAlignment = Alignment.CenterVertically,
                    horizontalArrangement = Arrangement.spacedBy(16.dp)
                ) {
                    // 发布时间
                    Text(
                        text = formatDate(post.createdAt),
                        style = MaterialTheme.typography.bodySmall,
                        color = Color(0xFF6C757D)
                    )
                    
                    // 点赞数
                    Row(
                        verticalAlignment = Alignment.CenterVertically,
                        horizontalArrangement = Arrangement.spacedBy(4.dp)
                    ) {
                        Icon(
                            imageVector = Icons.Default.ThumbUp,
                            contentDescription = "点赞",
                            modifier = Modifier.size(14.dp),
                            tint = Color(0xFF6C757D)
                        )
                        Text(
                            text = post.likeCount.toString(),
                            style = MaterialTheme.typography.bodySmall,
                            color = Color(0xFF6C757D)
                        )
                    }
                    
                    // 评论数
                    Row(
                        modifier = Modifier.clickable { onCommentClick() },
                        verticalAlignment = Alignment.CenterVertically,
                        horizontalArrangement = Arrangement.spacedBy(4.dp)
                    ) {
                        Icon(
                            imageVector = Icons.Default.Comment,
                            contentDescription = "评论",
                            modifier = Modifier.size(14.dp),
                            tint = Color(0xFF6C757D)
                        )
                        Text(
                            text = post.commentCount.toString(),
                            style = MaterialTheme.typography.bodySmall,
                            color = Color(0xFF6C757D)
                        )
                    }
                }
                
                // 操作按钮
                Row(
                    horizontalArrangement = Arrangement.spacedBy(8.dp)
                ) {
                    // 编辑按钮
                    IconButton(
                        onClick = onEditClick,
                        modifier = Modifier.size(32.dp)
                    ) {
                        Icon(
                            imageVector = Icons.Default.Edit,
                            contentDescription = "编辑",
                            modifier = Modifier.size(16.dp),
                            tint = Color(0xFF4361EE)
                        )
                    }
                    
                    // 删除按钮
                    IconButton(
                        onClick = onDeleteClick,
                        modifier = Modifier.size(32.dp)
                    ) {
                        Icon(
                            imageVector = Icons.Default.Delete,
                            contentDescription = "删除",
                            modifier = Modifier.size(16.dp),
                            tint = Color(0xFFD32F2F)
                        )
                    }
                }
            }
        }
    }
}

// 格式化日期
fun formatDate(dateString: String?): String {
    if (dateString == null) return "未知时间"
    
    return try {
        val inputFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.getDefault())
        val outputFormat = SimpleDateFormat("MM-dd HH:mm", Locale.getDefault())
        val date = inputFormat.parse(dateString)
        outputFormat.format(date ?: Date())
    } catch (e: Exception) {
        "未知时间"
    }
}

// 生成模拟数据
fun generateMockPosts(userId: Long, page: Int = 1): List<CommunityPost> {
    return if (page == 1) {
        listOf(
            CommunityPost(
                id = 1,
                userId = userId,
                author = "我",
                title = "今天完成了5公里跑步",
                content = "早上6点起床，完成了5公里晨跑，心率保持在150-160之间，感觉状态不错！",
                likeCount = 12,
                favoriteCount = 5,
                commentCount = 8,
                isLiked = false,
                isFavorited = false,
                createdAt = "2025-09-10T08:30:00",
                updatedAt = "2025-09-10T08:30:00"
            ),
            CommunityPost(
                id = 2,
                userId = userId,
                author = "我",
                title = "HIIT训练分享",
                content = "今天尝试了新的HIIT训练计划，30分钟内进行了8组高强度训练，消耗了约400卡路里。",
                likeCount = 25,
                favoriteCount = 12,
                commentCount = 15,
                isLiked = false,
                isFavorited = false,
                createdAt = "2025-09-09T19:45:00",
                updatedAt = "2025-09-09T19:45:00"
            ),
            CommunityPost(
                id = 3,
                userId = userId,
                author = "我",
                title = "健身计划分享",
                content = "制定了一个月的健身计划，包括力量训练和有氧运动，希望能坚持下去。",
                likeCount = 8,
                favoriteCount = 3,
                commentCount = 5,
                isLiked = false,
                isFavorited = false,
                createdAt = "2025-09-08T20:15:00",
                updatedAt = "2025-09-08T20:15:00"
            )
        )
    } else {
        emptyList()
    }
}

